<template>
  <div class="user-info">
    <v-navbar></v-navbar>
    <div class="user-wrapper">
      <icon-title :iconClass="userIcon" :text="userInfo"></icon-title>
      <div class="item">
        <div class="wrapper">
          <span class="text">头像</span>
          <div class="img" @click.stop="uploadHeadImg">
            <img :src="userData.img == undefined ? userImg:userData.img" width="40" height="40" alt="">
            <i class="icon"></i>
          </div>
          <input type="file" id="file" accept="image/*" @change="handleFile" class="hiddenInput"/>
        </div>
        <div class="wrapper" @click="_handleRender">
          <span class="text">昵称</span>
          <div class="text-wrapper">
            <span class="w-text">{{userData.nickName}}</span>
            <i class="icon"></i>
          </div>
        </div>
        <div class="wrapper">
          <span class="text">真实姓名</span>
          <span class="w-text">{{userData.realName}}</span>
        </div>
        <div class="wrapper border-none" @click="revise(telVal)">
          <span class="text">手机号码</span>
          <div class="text-wrapper">
            <span class="w-text">{{userData.phone}}</span>
            <i class="icon"></i>
          </div>
        </div>
      </div>
      <icon-title :iconClass="memberIcon" :text="memberInfo"></icon-title>
      <div class="item">
        <div class="wrapper" @click="revise(loginPwd)">
          <span class="text">修改登录密码</span>
          <i class="icon"></i>
        </div>
        <div class="wrapper border-none" @click="revise(payPwd)">
          <span class="text">修改资金密码</span>
          <i class="icon"></i>
        </div>
      </div>
    </div>
    <div class="copper-wrapper" v-show="cropperShow">
      <div class="cropper">
        <vue-cropper ref="cropper" :img="option.img" :output-size="option.size" :output-type="option.outputType"
                     :info="true" :full="option.full" :can-move="option.canMove" :can-move-box="option.canMoveBox"
                     :fixed-box="option.fixedBox" :original="option.original" :auto-crop="option.autoCrop"
                     :auto-crop-width="option.autoCropWidth" :auto-crop-height="option.autoCropHeight"
                     :center-box="option.centerBox" :high="option.high" :fixedNumber="option.fixedNumber"
                     :fixed="option.fixed"></vue-cropper>
      </div>
      <div class="cropper-btn">
        <button class="cropper-sub" @click="onCubeImg">确定</button>
      </div>
    </div>
  </div>
</template>

<script>
import VueCropper from '@c/vue-cropper/vue-cropper'
import userImg from '@imgs/self/user_img.png'
import navbar from '@c/navbar/navbar'
import iconTitle from '@c/iconTitle/iconTitle'
import Button from '@c/button/button'
import { mapState, mapMutations } from 'vuex'
import { vpost, sonpost, fpost, gpost, vlink } from '@api/axios'
import { tokenPost, jtpost, gtpost, tokenLink, jtget } from '@api/axiosByToken'
import { uploadOSS } from '@t/oss'

const TEL = 'tel' // 手机号
const LOGIN = 'login' //登录
const PAY = 'pay' //支付

export default {
	name: 'UserInfo',
	data() {
		return {
			userImg,
			userIcon: 'set', //小标题类名
			userInfo: '个人信息', //小标题名
			memberIcon: 'member', //小标题类名
			memberInfo: '会员安全信息', //小标题名
			telVal: TEL,
			loginPwd: LOGIN,
			payPwd: PAY,
			userData: {}, //用户信息
			client: '',
			fileSize: 5000000,
			imgUrl: '',
			// 截图传值
			option: {
				img: '',
				size: 1,
				full: false,
				outputType: 'jpeg',
				canMove: true,
				fixedBox: false,
				original: false,
				canMoveBox: true,
				autoCrop: true,
				// 只有自动截图开启 宽度高度才生效
				autoCropWidth: 300,
				autoCropHeight: 300,
				centerBox: false,
				high: true,
				fixed: true,
				fixedNumber: [1, 1],
			},
			cropperShow: false,
			fileinfo: {},
			fileUpload: '',
			updateNick: '', //修改昵称名
		}
	},
	components: {
		'v-navbar': navbar,
		'icon-title': iconTitle,
		'v-button': Button,
		'vue-cropper': VueCropper,
	},
	computed: {
		...mapState(['wtitle', 'rback']),
	},
	methods: {
		...mapMutations(['WTITLE', 'RBACK', 'REVISE', 'LOADDING']),
		// 跳转修改页面
		revise(type) {
			if (
				type === 'pay' &&
				window.localStorage.tradPassword === 'false'
			) {
				this.$router.push('/setPay')
				return
			}
			this.REVISE(type)
			this.$router.push('/revise')
		},
		// 点击头像
		uploadHeadImg() {
			this.$el.querySelector('.hiddenInput').click()
		},
		// 将本地图片上传
		handleFile(event) {
			console.log(event)
			console.log(event.target.files[0])
			this.cropperShow = true
			this.uploadImg(event)
			this.fileUpload = event.target.files[0].name
		},
		// 将裁剪完图片上传oss
		async uploadImage(event) {
			this.cropperShow = false
			this.imgUrl = await uploadOSS(event, 0)
			if (this.imgUrl) {
				this.changeUserIcon()
			}
		},
		// 上传图片
		uploadImg(e) {
			//上传图片
			// this.option.img
			var file = e.target.files[0]
			if (!/\.(gif|jpg|jpeg|png|bmp|GIF|JPG|PNG)$/.test(e.target.value)) {
				alert('图片类型必须是.gif,jpeg,jpg,png,bmp中的一种')
				return false
			}
			var reader = new FileReader()
			console.log(e.target.result)
			reader.onload = e => {
				let data
				if (typeof e.target.result === 'object') {
					// 把Array Buffer转化为blob 如果是base64不需要
					data = window.URL.createObjectURL(
						new Blob([e.target.result]),
					)
				} else {
					data = e.target.result
				}
				this.option.img = data
			}
			// 转化为base64
			// reader.readAsDataURL(file)
			// 转化为blob
			reader.readAsArrayBuffer(file)
		},
		// 确定裁剪
		onCubeImg() {
			// 获取cropper的截图的base64 数据
			this.$refs.cropper.getCropData(data => {
				this.fileinfo.url = data
				// this.isShowCropper = false

				//先将显示图片地址清空，防止重复显示
				this.option.img = ''

				//将剪裁后base64的图片转化为file格式
				// let file = this.convertBase64UrlToBlob(data)
				let file = this.dataURLtoFile(data, this.fileUpload)

				//将剪裁后的图片执行上传
				this.uploadImage(file)
			})
		},
		// 将base64的图片转换为file文件
		dataURLtoFile(dataurl, filename) {
			//将base64转换为文件
			var arr = dataurl.split(','),
				mime = arr[0].match(/:(.*?);/)[1],
				bstr = atob(arr[1]),
				n = bstr.length,
				u8arr = new Uint8Array(n)
			while (n--) {
				u8arr[n] = bstr.charCodeAt(n)
			}
			return new File([u8arr], filename, { type: mime })
		},
		// 修改用户头像
		changeUserIcon() {
			let changeUrl = {
				headPortrait: this.imgUrl,
				userId: localStorage.getItem('userId'),
			}
			tokenPost(tokenLink.user.changeUserIcon, changeUrl).then(re => {
				if (re.status == 0) {
					console.log(re)
					this._getUserInfo()
				}
			})
		},
		// ================================获取用户信息👇=================================//
		_getUserInfo() {
			let userId = window.localStorage.userId
			let userInfoID = {
				userId: userId,
			}
			tokenPost(tokenLink.user.info, userInfoID).then(re => {
				this.LOADDING(false)
				if (re.status == 0) {
					this.userData = re.data
				} else {
					this.$Message.success(re.msg)
				}
			})
		},
		// ================================获取用户信息👆=================================//
		_handleRender() {
			this.$Modal.confirm({
				render: h => {
					return h('Input', {
						props: {
							value: this.userData.nickName,
							autofocus: true,
							placeholder: '请输入昵称',
						},
						on: {
							input: val => {
								this.updateNick = val
							},
						},
					})
				},
				onOk: () => {
					if (this.updateNick === '') {
						return
					}
					let nickName = {
						userId: window.localStorage.getItem('userId'),
						nickName: this.updateNick,
					}
					tokenPost(tokenLink.user.updateNick, nickName).then(re => {
						if (re.status === 0) {
							this.userData.nickName = this.updateNick
							this.$Message.success('修改成功')
						} else {
							this.$Message.error(re.msg)
						}
					})
				},
			})
		},
	},
	created() {
		this.WTITLE('个人资料')
		this.RBACK(true)
		this.LOADDING(true)
		this._getUserInfo()
		console.log(VueCropper)
	},
}
</script>
<style scoped>
.hiddenInput {
	display: none;
}
</style>
